package com.guet.main.controller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guet.common.utils.R;
import com.guet.main.entity.User;
import com.guet.main.entity.vo.RetPassword;
import com.guet.main.entity.vo.UserLoginVo;
import com.guet.main.service.UserService;
import com.guet.main.utils.JWTUtils;
import com.guet.main.utils.MailClient;
import com.guet.main.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * user 前端控制器
 * </p>
 *
 * @author csp
 * @since 2022-07-29
 */
@RestController
@RequestMapping("/main/user")
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private MailClient mailClient;
    @Autowired
    private RedisUtil redisUtil;

    @PostMapping("/send_mail/{mail}")
    @ApiOperation("发送邮件")
    public R sendMail(@PathVariable String mail){
        //判断是否合法
        if(!StringUtils.isNotEmpty(mail)){
            return R.error();
        }
        return mailClient.sendMail(mail)?R.ok():R.error();
    }

    @GetMapping("/getCode/{mail}")
    @ApiOperation("获取验证码")
    public R getCode(@PathVariable String mail){
        Object o = redisUtil.get(mail);
        if(o!=null){
            return R.ok().data("code",(String) o);
        }else {
            return R.error();
        }
    }

    @PostMapping("/retPassword")
    @ApiOperation("找回密码")
    public R retPassword(@RequestBody RetPassword retPassword){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",retPassword.getAccount());
        queryWrapper.eq("mail",retPassword.getMail());
        List<User> list = userService.list(queryWrapper);
        if(!list.isEmpty()){
            User user = list.get(0);
            user.setPassword(SecureUtil.md5(retPassword.getPassword()));
            boolean b = userService.updateById(user);
            return b?R.ok():R.error();
        }
       return R.error();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public R login(HttpServletResponse response, @RequestBody UserLoginVo userLoginVo){
        //判断是否合法
        String account = userLoginVo.getAccount();
        String password = userLoginVo.getPassword();
        if(!StringUtils.isNotEmpty(account)&&StringUtils.isNotEmpty(password)){
            return R.error().data("msg","账号或者密码格式错误");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",account);
        List<User> list = userService.list(queryWrapper);
        if(list.isEmpty()){
            return R.error().data("msg","账号不存在，请联系管理员");
        }
        User user = list.get(0);
        String password_real = user.getPassword();
        password = SecureUtil.md5(password);
        if(password.equals(password_real)){
            String id = user.getId();
            String token = JWTUtils.createToken(id);
            response.setHeader(JWTUtils.USER_LOGIN_TOKEN,token);
            return R.ok().data("msg","登录成功").data("token",token);
        }else{
            return R.error().data("msg","账号或密码错误");
        }
    }

    @GetMapping("/getUserInfo")
    @ApiOperation("获取用户信息")
    public R getUserInfo( HttpServletRequest request){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        User byId = userService.getById(userId);
        return R.ok().data("user",byId);
    }

    @GetMapping("/list")
    @ApiOperation("获取所有用户")
    public R list(){
        List<User> list = userService.list(null);
        return R.ok().data("list",list);
    }

    @GetMapping("/getById/{id}")
    @ApiOperation("通过id获取")
    public R getByID(@PathVariable String id){
        User byId = userService.getById(id);
        return R.ok().data("user",byId);
    }

    @PostMapping("/add")
    @ApiOperation("通过excel新增用户")
    public R add(MultipartFile file){
        userService.saveSubject(file,userService);
        return R.ok();
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("通过id删除用户")
    public R delete(@PathVariable String id){
        boolean b = userService.removeById(id);
        return b?R.ok():R.error();
    }

    @PutMapping("/update")
    @ApiOperation("更新用户")
    public R update(@RequestBody User user){
        user.setPassword(SecureUtil.md5(user.getPassword()));
        boolean b = userService.updateById(user);
        return b?R.ok():R.error();
    }

    @GetMapping("/reset/{id}")
    @ApiOperation("重置密码")
    public R reset(@PathVariable String id){
        User user = userService.getById(id);
        String password = user.getAccount();
        return R.ok().data("password",password);
    }
    @GetMapping("/search/{key}")
    @ApiOperation("搜索用户")
    public R search(@PathVariable String key){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("account",key);
        List<User> list = userService.list(queryWrapper);
        return R.ok().data("list",list);
    }
}

